package handler

import (
	"context"
	"go_final/mxshop_srvs/userop_srv/global"
	"go_final/mxshop_srvs/userop_srv/model"
	user_favpb "go_final/mxshop_srvs/userop_srv/proto/protofile/user_fav"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"google.golang.org/protobuf/types/known/emptypb"
)

type UserFavServer struct{}

func (u UserFavServer) GetFavList(c context.Context, request *user_favpb.UserFavRequest) (*user_favpb.UserFavListResponse, error) {
	var userFavs []model.UserFav
	res := global.DB.Where(model.UserFav{
		UserID: request.UserID,
		Goods:  request.GoodID, // 用户查询这个商品被收藏了多少次(本项目没有用到)
	}).Find(&userFavs)

	if res.Error != nil {
		return nil, res.Error
	}

	rsp := user_favpb.UserFavListResponse{
		Total: int32(res.RowsAffected),
	}

	for _, userFav := range userFavs {
		rsp.Data = append(rsp.Data, &user_favpb.UserFavResponse{
			UserID: userFav.UserID,
			GoodID: userFav.Goods,
		})
	}

	return &rsp, nil
}

func (u UserFavServer) AddUserFav(c context.Context, request *user_favpb.UserFavRequest) (*emptypb.Empty, error) {
	// TODO 为了严谨性, 需要调用用户服务查询userID存不存在, 调用商品服务查询商品存不存在
	userFav := model.UserFav{
		UserID: request.UserID,
		Goods:  request.GoodID,
	}

	res := global.DB.Create(&userFav)
	if res.Error != nil {
		return nil, res.Error
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.Internal, "用户加入收藏失败")
	}

	return &emptypb.Empty{}, nil
}

func (u UserFavServer) DeleteUserFav(c context.Context, request *user_favpb.UserFavRequest) (*emptypb.Empty, error) {
	res := global.DB.Unscoped().Where(model.UserFav{
		UserID: request.UserID,
		Goods:  request.GoodID,
	}).Delete(&model.UserFav{})

	if res.Error != nil {
		return nil, res.Error
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.Internal, "用户删除收藏失败")
	}

	return &emptypb.Empty{}, nil
}

// GetUserFavDetail 查询用户是否收藏了该商品(用于页面展示)
func (u UserFavServer) GetUserFavDetail(c context.Context, request *user_favpb.UserFavRequest) (*emptypb.Empty, error) {
	userFav := model.UserFav{}

	res := global.DB.Where(model.UserFav{
		UserID: request.UserID,
		Goods:  request.GoodID,
	}).Find(&userFav)

	if res.Error != nil {
		return nil, res.Error
	}

	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "记录不存在")
	}

	return &emptypb.Empty{}, nil
}
